import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Personal from '../views/Personal.vue'
import Edit from '../views/Edit.vue'
import Test from '../views/Test.vue'
import Follow from '../views/Follow.vue'
import Star from '../views/Star.vue'
import PostDetail from '../views/PostDetail.vue'
import MoreComment from '../views/MoreComment.vue'
import Comment from '../views/Comment.vue'
import Search from '../views/Search.vue'
import Manage from '../views/Manage.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: function () {
      return import(/* webpackChunkName: "about" */ '../views/About.vue')
    }
  },
  {
    path: '/login',
    component: Login

  },
  {
    path: '/register',
    component: Register
  },
  {
    path: '/personal',
    component: Personal,
    meta:{
      needAuth:true
    }
  },
  {
    path:'/edit',
    component:Edit,
    meta:{
      needAuth:true
    }
  },
  {
    path:'/test',
    component:Test
  },
  {
    path:'/follow',
    component:Follow,
    meta:{
      needAuth:true
    }
  },
  {
    path:'/star',
    component:Star,
    meta:{
      needAuth:true
    }
  },
  {
    path:'/postdetail/:id',
    component:PostDetail
  },
  {
    path:'/morecomment/:id',
    component:MoreComment
  },
  {
    path:'/comment',
    component:Comment,
    meta:{
      needAuth:true
    }
  },
  {
    path:'/search',
    component:Search
  },
  {
    path:'/manage',
    component:Manage
  }

]

const router = new VueRouter({
  routes
})
// 添加全局路由守卫
// 拦截住所有跳转, 执行回调函数
router.beforeEach((to, from, next) => {

  console.log('看看当前路由信息是什么');
  console.log(to.meta);
  // 如果我进入的地方是个人中心

   // 方法一、 最简单的写法, 直接 || 或逻辑进行判断
  // if (to.path == '/personal' || to.path == '/edit') {

    //方法二、将需要校验的页面配置成一个数组
    // const pagesNeedAuth = [
    //   '/profile',
    //   '/edit'
    // ]


    //如果我进入的地方是个人中心
    // if(pagesNeedAuth.indexOf(to.path)>-1){
    // 判断 token 是否存在


   //方法三、 第三种判断方法, 可以给页面路由配置设置 meta, 在这里判断即可
    if(to.meta.needAuth){
    if (localStorage.getItem('token')) {
      // 存在则放行
      return next()
    } else {
      // 如果不存在,跳转到登录页
      return router.push('/login').catch((err) => { })
    }
  }
  return next();
})

export default router
